<!--
	o   Contains  the list of messages the user has Sent/Received
-->


<h1>Messages Page</h1>
<?php
include('connect.php');
$USRID = $_SESSION['USRID'];
$query = "SELECT * FROM COMMUNICATIONS WHERE USRID='$USRID'";

if (!isset($_GET['UCNID'])){
	echo <<<_END
	<a href="?page=new_message">Compose Message</a>
	<table border=2>
	<tr>
		<th>DATE</th><th>TITLE</th>
	</tr>
_END;
	$query .= ";";
	$result = mysql_query($query);
	if (!$result) die ("Database access failed: " . mysql_error());
	$rows = mysql_num_rows($result);
	for ($i = 0 ; $i < $rows ; ++$i) 
	{
		$COM_DATE = mysql_result($result,$i,'COM_DATE');
		$TITLE = mysql_result($result,$i,'TITLE');
		$UCNID = mysql_result($result,$i,'UCNID');
		$READ = (mysql_result($result,$i,'COM_VIEWED')=='YES');
		echo "<tr><th>";
		if(!$READ) echo "<u><i>";
		echo "$COM_DATE";
		if(!$READ) echo "</u></i>";
		echo "</th><th><a href='?page=messages&UCNID=$UCNID'>";
		if(!$READ) echo "<u><i>";
		echo "$TITLE";
		if(!$READ) echo "</u></i>";
		echo"</a></th></tr>";
	}
	echo "</table>";
}
else
{
	$UCNID = $_GET['UCNID'];
	$query .= " AND UCNID='$UCNID'";
	$result = mysql_query($query);
	if (!$result) die ("Database access failed: " . mysql_error());
	if(mysql_num_rows($result)>0 && mysql_result($result,0,'USRID') == $USRID)
	{
		$COM_DATE = mysql_result($result,0,'COM_DATE');
		$TITLE = mysql_result($result,0,'TITLE');
		$MSG = nl2br(mysql_result($result,0,'MESSAGE'));
		$FROMID = mysql_result($result,0,'FROMID');
		echo <<<_END
		<h2>$TITLE</h2>
		<h6>$COM_DATE</h6>
		<p><a href='?page=new_message&to=$FROMID'>[reply]</a> <a href='?page=new_appointment&to=$FROMID'>[make appointment]</a></p>
		<p>$MSG</p>
_END;
		// Mark message as read.
		$query = "UPDATE COMMUNICATIONS SET COM_VIEWED='YES' WHERE UCNID='$UCNID';";
		$result = mysql_query($query);
		if (!$result) die ("Database access failed: " . mysql_error());
	}
}
include('disconnect.php');
?>
